package com.ruoyi.web.controller.quality;

import cn.dev33.satoken.annotation.SaCheckPermission;
import cn.hutool.core.collection.CollUtil;
import com.ruoyi.common.Rejectsn;
import com.ruoyi.common.annotation.Log;
import com.ruoyi.common.annotation.RepeatSubmit;
import com.ruoyi.common.core.controller.BaseController;
import com.ruoyi.common.core.domain.PageQuery;
import com.ruoyi.common.core.domain.R;
import com.ruoyi.common.core.page.TableDataInfo;
import com.ruoyi.common.core.validate.AddGroup;
import com.ruoyi.common.core.validate.EditGroup;
import com.ruoyi.common.enums.BusinessType;
import com.ruoyi.common.excel.ExcelResult;
import com.ruoyi.common.utils.poi.ExcelUtil;
import com.ruoyi.listener.losses.RejectsnLossesImportListener;
import com.ruoyi.quality.domain.bo.QualityRejectsnLossesBo;
import com.ruoyi.quality.domain.vo.QualityRejectsnLossesImportVo;
import com.ruoyi.quality.domain.vo.QualityRejectsnLossesVo;
import com.ruoyi.quality.service.IQualityRejectsnLossesService;
import lombok.RequiredArgsConstructor;
import org.springframework.http.MediaType;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletResponse;
import javax.validation.constraints.NotEmpty;
import javax.validation.constraints.NotNull;
import java.util.*;
import java.util.stream.Collectors;

/**
 * 不合格品损失
 *
 * @author yanjun
 * @date 2023-09-12
 */
@Validated
@RequiredArgsConstructor
@RestController
@RequestMapping("/quality/rejectsnLosses")
public class QualityRejectsnLossesController extends BaseController {

    private final IQualityRejectsnLossesService iQualityRejectsnLossesService;

    /**
     * 查询不合格品损失列表
     */
    @SaCheckPermission("quality:rejectsnLosses:list")
    @GetMapping("/list")
    public TableDataInfo<QualityRejectsnLossesVo> list(QualityRejectsnLossesBo bo, PageQuery pageQuery) {
        return iQualityRejectsnLossesService.queryPageList(bo, pageQuery);
    }

    /**
     * 查询不合格品损失列表
     */
    @SaCheckPermission("quality:rejectsnLosses:list")
    @GetMapping("/listSelect")
    public TableDataInfo<QualityRejectsnLossesVo> listSelect(QualityRejectsnLossesBo bo, PageQuery pageQuery) {
        return iQualityRejectsnLossesService.queryPageListSelect(bo, pageQuery);
    }

    /**
     * 导出全部不合格品损失列表
     */
    @SaCheckPermission("quality:rejectsnLosses:export")
    @Log(title = "不合格品损失", businessType = BusinessType.EXPORT)
    @PostMapping("/exportAll")
    public void exportAll(QualityRejectsnLossesBo bo, HttpServletResponse response) {
        Map<String, String> map = new HashMap<>();
        List<QualityRejectsnLossesVo> list = iQualityRejectsnLossesService.queryList(bo);
        ExcelUtil.exportTemplate(CollUtil.newArrayList(map, list), "单列表.xlsx", "excel/不合格信息单导出表.xlsx", response);
    }

    /**
     * 导出返工返修不合格品损失列表
     */
    @SaCheckPermission("quality:rejectsnLosses:export")
    @Log(title = "不合格品损失", businessType = BusinessType.EXPORT)
    @PostMapping("/exportRework")
    public void exportRework(QualityRejectsnLossesBo bo, HttpServletResponse response) {
        Map<String, String> map = new HashMap<>();
        List<QualityRejectsnLossesVo> list = iQualityRejectsnLossesService.queryList(bo);
        List<QualityRejectsnLossesVo> voList = list.stream().filter(s->s.getHandlingConclusion().equals(Rejectsn.Repair) || s.getHandlingConclusion().equals(Rejectsn.Rework)).filter(s->!s.getDeptAbbreviation().equals(Rejectsn.DEPT_DEFAULT)).collect(Collectors.toList());
        ExcelUtil.exportTemplate(CollUtil.newArrayList(map, voList), "单列表.xlsx", "excel/返工返修导出表.xlsx", response);
    }

    /**
     * 导出选择不合格品损失列表
     */
    @SaCheckPermission("quality:rejectsnLosses:export")
    @Log(title = "不合格品损失", businessType = BusinessType.EXPORT)
    @PostMapping("/exportSelect/{rejectsnIds}")
    public void exportSelect(@NotEmpty(message = "主键不能为空")
                                 @PathVariable Collection<Long> rejectsnIds, HttpServletResponse response) {
        List<QualityRejectsnLossesVo> list = iQualityRejectsnLossesService.queryByIds(rejectsnIds);
        ExcelUtil.exportExcel(list, "不合格品损失", QualityRejectsnLossesVo.class, response);
    }

    /**
     * 导出选择毛坯列表
     */
    @SaCheckPermission("quality:rejectsnLosses:export")
    @Log(title = "不合格品损失", businessType = BusinessType.EXPORT)
    @PostMapping("/exportSelectBlank")
    public void exportSelectBlank(QualityRejectsnLossesBo bo, HttpServletResponse response) {
        Map<String, String> map = new HashMap<>();
        List<QualityRejectsnLossesVo> list = iQualityRejectsnLossesService.queryList(bo);
        ExcelUtil.exportTemplate(CollUtil.newArrayList(map, list), "单列表.xlsx", "excel/毛坯导出表.xlsx", response);
    }

    /**
     * 导出选择零件列表
     */
    @SaCheckPermission("quality:rejectsnLosses:export")
    @Log(title = "不合格品损失", businessType = BusinessType.EXPORT)
    @PostMapping("/exportSelectPart")
    public void exportSelectPart(QualityRejectsnLossesBo bo, HttpServletResponse response) {
        Map<String, String> map = new HashMap<>();
        List<QualityRejectsnLossesVo> list = iQualityRejectsnLossesService.queryList(bo);
        ExcelUtil.exportTemplate(CollUtil.newArrayList(map, list), "单列表.xlsx", "excel/零件导出表.xlsx", response);
    }

    /**
     * 导出手动查询列表
     */
    @SaCheckPermission("quality:rejectsnLosses:export")
    @Log(title = "不合格品损失", businessType = BusinessType.EXPORT)
    @PostMapping("/exportSelectMov")
    public void exportSelectMov(QualityRejectsnLossesBo bo, HttpServletResponse response) {
        Map<String, String> map = new HashMap<>();
        List<QualityRejectsnLossesVo> list = iQualityRejectsnLossesService.queryList(bo);
        list.forEach(item->{
            String partNumber = item.getPartNumber();
            String[] parts = partNumber.split("-");
            if (parts.length > 1) {
                item.setMovNumber(parts[parts.length - 1]);
            } else {
                item.setMovNumber(partNumber); // 或者返回其他默认值，表示没有找到匹配的文字
            }

        });
        ExcelUtil.exportTemplate(CollUtil.newArrayList(map, list), "单列表.xlsx", "excel/手动导出表.xlsx", response);
    }

    /**
     * 导入数据
     *
     * @param file          导入文件
     * @param updateSupport 是否更新已存在数据
     */
    @Log(title = "用户管理", businessType = BusinessType.IMPORT)
    @SaCheckPermission("quality:rejectsnLosses:import")
    @PostMapping(value = "/importData", consumes = MediaType.MULTIPART_FORM_DATA_VALUE)
    public R<Void> importData(@RequestPart("file") MultipartFile file, boolean updateSupport) throws Exception {
        ExcelResult<QualityRejectsnLossesImportVo> result = ExcelUtil.importExcel(file.getInputStream(), QualityRejectsnLossesImportVo.class, new RejectsnLossesImportListener(updateSupport));
        return R.ok(result.getAnalysis());
    }

    /**
     * 获取导入模板
     */
    @PostMapping("/importTemplate")
    public void importTemplate(HttpServletResponse response) {
        ExcelUtil.exportExcel(new ArrayList<>(), "不合格品损失",  QualityRejectsnLossesVo.class, response);
    }

    /**
     * 获取不合格品损失详细信息
     *
     * @param rejectsnId 主键
     */
    @SaCheckPermission("quality:rejectsnLosses:query")
    @GetMapping("/{rejectsnId}")
    public R<QualityRejectsnLossesVo> getInfo(@NotNull(message = "主键不能为空")
                                     @PathVariable Long rejectsnId) {
        return R.ok(iQualityRejectsnLossesService.queryById(rejectsnId));
    }

    /**
     * 新增不合格品损失
     */
    @SaCheckPermission("quality:rejectsnLosses:add")
    @Log(title = "不合格品损失", businessType = BusinessType.INSERT)
    @RepeatSubmit()
    @PostMapping()
    public R<Void> add(@Validated(AddGroup.class) @RequestBody QualityRejectsnLossesBo bo) {
        return toAjax(iQualityRejectsnLossesService.insertByBo(bo));
    }

    /**
     * 修改不合格品损失
     */
    @SaCheckPermission("quality:rejectsnLosses:edit")
    @Log(title = "不合格品损失", businessType = BusinessType.UPDATE)
    @RepeatSubmit()
    @PutMapping()
    public R<Void> edit(@Validated(EditGroup.class) @RequestBody QualityRejectsnLossesBo bo) {
        return toAjax(iQualityRejectsnLossesService.updateByBo(bo));
    }

    /**
     * 删除不合格品损失
     *
     * @param rejectsnIds 主键串
     */
    @SaCheckPermission("quality:rejectsnLosses:remove")
    @Log(title = "不合格品损失", businessType = BusinessType.DELETE)
    @DeleteMapping("/{rejectsnIds}")
    public R<Void> remove(@NotEmpty(message = "主键不能为空")
                          @PathVariable Long[] rejectsnIds) {
        return toAjax(iQualityRejectsnLossesService.deleteWithValidByIds(Arrays.asList(rejectsnIds), true));
    }
}
